package com.spr.application;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.spr.bean.order.OrderClothesDTO;
import com.spr.bean.order.OrderClothesFeeDTO;
import com.spr.bean.order.OrderPayDTO;
import com.spr.cache.UrlCache;
import com.spr.config.WebConfig;
import com.spr.util.JsonUtil;
import com.spr.util.PrintUtils;
import com.spr.util.QrcodeUtil;
import com.wpx.IBluetoothPrint;
import com.wpx.WPXMain;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class WebActivity extends AppCompatActivity {

//    private ValueCallback<Uri> uploadMessage;
//    private ValueCallback<Uri[]> uploadMessageAboveL;
//    private final static int FILE_CHOOSER_RESULT_CODE = 10000;
//
//    private WebView webView;
//
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_web);
//
//        webView = (WebView)this.findViewById(R.id.webBrowser);
//
//        WebSettings settings = webView.getSettings();
//        settings.setAllowFileAccess(true);
//        settings.setUseWideViewPort(true);
//        settings.setLoadWithOverviewMode(true);
//        settings.setJavaScriptEnabled(true);
//
//
//
//        webView.addJavascriptInterface(new WebOPeration(this), "client");
//
//        syncCookie(this);
//
//        webView.loadUrl(WebConfig.EJQ_DOMIN + WebConfig.ORDER_PATH);
//        //webView.getSettings().
//       webView.setWebViewClient(new WebViewClient(){
//
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
//                return super.shouldOverrideUrlLoading(view, url);
//            }
//
//        });
//
//       webView.setWebChromeClient(new WebChromeClient() {
//
//
//        });
//
//    }



    private   WebView mWebView;


    private ValueCallback<Uri> mUploadMessage;// 表单的数据信息
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private final static int FILECHOOSER_RESULTCODE = 10000;// 表单的结果回调
    private Uri imageUri;

    private static boolean refreshCookis = true;

    @Override
    protected void onStart() {
        super.onStart();

        if(refreshCookis){
            syncCookie(this);
            refreshCookis = false;
        }

        if(UrlCache.qrCodeSkipUrl!=null){
            mWebView.loadUrl(UrlCache.qrCodeSkipUrl);
            UrlCache.qrCodeSkipUrl = null;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        mWebView=(WebView) this.findViewById(R.id.webBrowser);


        //mWebView.getSettings().setJavaScriptEnabled(true);
        //mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        WebSettings settings = mWebView.getSettings();
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);

        mWebView.addJavascriptInterface(new WebOPeration(this), "client");
        if(refreshCookis){
            syncCookie(this);
            refreshCookis = false;
        }

        mWebView.loadUrl(WebConfig.EJQ_DOMIN + WebConfig.ORDER_PATH);

        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient(){

            @Override
            public boolean onShowFileChooser(WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             FileChooserParams fileChooserParams) {
                mUploadCallbackAboveL=filePathCallback;
                take();
                return true;
            }


            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage=uploadMsg;
                take();
            }
            public void openFileChooser(ValueCallback<Uri> uploadMsg,String acceptType) {
                mUploadMessage=uploadMsg;
                take();
            }
            public void openFileChooser(ValueCallback<Uri> uploadMsg,String acceptType, String capture) {
                mUploadMessage=uploadMsg;
                take();
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
        if(intentResult != null) {
            if(intentResult.getContents() == null) {
                //  Toast.makeText(this,"内容为空",Toast.LENGTH_LONG).show();
            } else {
                //Toast.makeText(this,"扫描成功",Toast.LENGTH_LONG).show();
                // ScanResult 为 获取到的字符串
                String sanResult = intentResult.getContents();

                mWebView.loadUrl(sanResult);
            }
        } else {

        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==FILECHOOSER_RESULTCODE)
        {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            }
            else  if (mUploadMessage != null) {

                if (result != null) {
                    String path = getPath(getApplicationContext(),
                            result);
                    Uri uri = Uri.fromFile(new File(path));
                    mUploadMessage
                            .onReceiveValue(uri);
                } else {
                    mUploadMessage.onReceiveValue(imageUri);
                }
                mUploadMessage = null;



            }
        }
        }
    }



    @SuppressWarnings("null")
    @TargetApi(Build.VERSION_CODES.BASE)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILECHOOSER_RESULTCODE
                || mUploadCallbackAboveL == null) {
            return;
        }

        Uri[] results = null;

        if (resultCode == Activity.RESULT_OK) {

            if (data == null) {

                results = new Uri[]{imageUri};
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();

                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }

                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        if(results!=null){
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        }else{
            results = new Uri[]{imageUri};
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        }

        return;
    }



    private void take(){
        File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyApp");
        // Create the storage directory if it does not exist
        if (! imageStorageDir.exists()){
            imageStorageDir.mkdirs();
        }
        File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        imageUri = Uri.fromFile(file);

        final List<Intent> cameraIntents = new ArrayList<Intent>();
        final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        final PackageManager packageManager = getPackageManager();
        final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
        for(ResolveInfo res : listCam) {
            final String packageName = res.activityInfo.packageName;
            final Intent i = new Intent(captureIntent);
            i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            i.setPackage(packageName);
            i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            cameraIntents.add(i);

        }
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        Intent chooserIntent = Intent.createChooser(i,"Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
        WebActivity.this.startActivityForResult(chooserIntent,  FILECHOOSER_RESULTCODE);
    }

    @SuppressLint("NewApi")
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }


    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null) cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }




    // 设置cookie
    private static void syncCookie(Context context) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();
        cookieManager.removeSessionCookie();//移除

        cookieManager.setCookie(WebConfig.EJQ_DOMIN , LoginActivity.cookieVal);//cookies是在HttpClient中获得的cookie
        CookieSyncManager.getInstance().sync();
    }

    //清空所有Cookie
    public static void clearCookie(Context context) {

           CookieSyncManager.createInstance(context);  //Create a singleton CookieSyncManager within a context
           CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
           cookieManager.removeAllCookie();// Removes all cookies.
           CookieSyncManager.getInstance().sync(); // forces sync manager to sync now
    }
    public static class WebOPeration{

       private  Activity mActivity;

        public WebOPeration(Activity mActivity) {
            this.mActivity = mActivity;
        }

        @JavascriptInterface
        public void logout() {

            clearCookie(mActivity);
            refreshCookis = true;

            Intent intent = new Intent(mActivity, LoginActivity.class);
            intent.putExtra(LoginActivity.autoLoginKey,false);
            //intent.getExtras().putBoolean(LoginActivity.autoLoginKey,false);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            mActivity.startActivity(intent);

        }

        @JavascriptInterface
        public void openScan() {

           // Toast.makeText(mActivity,"openScan",Toast.LENGTH_SHORT).show();

          /*
          //zxing
          new IntentIntegrator(mActivity)
                    .setOrientationLocked(false)
                    .setCaptureActivity(CustomScanActivity.class) // 设置自定义的activity是CustomActivity
                    .initiateScan(); // 初始化扫描
                    */

            Intent intent = new Intent(mActivity, ZxingtScanActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            mActivity.startActivity(intent);

        }

        /**
         * 打印二维码
         * @param orderNo
         */
        @JavascriptInterface
        public void printQrcode(String orderNo,String staffNo) {

            Toast.makeText(mActivity,"prinitQcrode",Toast.LENGTH_SHORT).show();

            //检测蓝牙是否连接上
            if(WPXMain.isConnected()){
                IBluetoothPrint imgbp = WPXMain.getBluetoothPrint();
                IBluetoothPrint.Describe des = new IBluetoothPrint.Describe();
                des.setGravity((byte) IBluetoothPrint.GRAVITY_CENTER);
                des.setWidth(280);
                des.setHeight(280);

                StringBuilder text = new StringBuilder("广西兆泳\n");
                text.append("收件员工号：").append(staffNo).append("\n");
                imgbp.printText(text.toString());

                StringBuilder url = new StringBuilder(WebConfig.EJQ_DOMIN).append(WebConfig.QRCODE_URL).append(orderNo);
                imgbp.printBitmap(QrcodeUtil.encodeAsBitmap(url.toString()), des);

                System.out.println(text);
                imgbp.printText("\n\n\n\n\n");

            }else{//未连接跳转到蓝牙设备列表
                Intent intent = new Intent(mActivity, BluetoothChoiceActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                mActivity.startActivity(intent);

            }

        }

        @JavascriptInterface
        public void printFeeList(String data) {

            //Toast.makeText(mActivity,"prinitQcrode",Toast.LENGTH_SHORT).show();
            OrderPayDTO order =  JsonUtil.jsonToObject(data, OrderPayDTO.class);

            //检测蓝牙是否连接上
            if(WPXMain.isConnected()){
                IBluetoothPrint imgbp = WPXMain.getBluetoothPrint();
                IBluetoothPrint.Describe des = new IBluetoothPrint.Describe();
                des.setGravity((byte) IBluetoothPrint.GRAVITY_LEFT);

                StringBuilder text = new StringBuilder();
                text.append(PrintUtils.printTwoData("交易编号",order.getOrderNo()+ "\n"));

                if(!order.getOrderClothess().isEmpty()){
                    OrderClothesDTO od = order.getOrderClothess().get(0);
                    text.append(PrintUtils.printTwoData("联系人",od.getRecvName()+"\n"));
                    text.append(PrintUtils.printTwoData("收件地址",od.getRecvCity()+od.getRecvArea()+
                            od.getRecvSecArea()+od.getRecvAddress()+ "\n"));
                    text.append(PrintUtils.printTwoData("是否加急",od.getIsUrgent()?"是":"否"+ "\n"));
                }

                text.append("--------------------------------\n");

                text.append(PrintUtils.printThreeData("名称", "数量", "金额\n"));
                text.append("--------------------------------\n");

                for (OrderClothesFeeDTO fee:order.getFees()) {
                    text.append(PrintUtils.printThreeData(fee.getClothesName(), fee.getQuantity().toString(),fee.getAmount()+ "\n"));
                }
                text.append("--------------------------------\n");
                text.append(PrintUtils.printTwoData("合计",order.getTotalAmount()+"\n"));
                if(order.getOffsetAmount()!=null && order.getScoreAmount()!=null){
                    text.append(PrintUtils.printTwoData("折扣", order.getOffsetAmount().add(order.getScoreAmount())+"\n"));
                }

                text.append("--------------------------------\n");
                text.append(PrintUtils.printTwoData("应收", order.getPayAmount()+"\n"));
                text.append("--------------------------------\n");

                text.append("委托人签名：");
                text.append("\n\n\n");
                text.append("收件人签名：");
                text.append("\n\n\n\n\n\n\n");


//                text.append(PrintUtils.printTwoData("订单编号", "201507161515\n"));
//                text.append(PrintUtils.printTwoData("订单编号", "201507161515\n"));
//                text.append(PrintUtils.printTwoData("点菜时间", "2016-02-16 10:46\n"));
//                text.append(PrintUtils.printTwoData("上菜时间", "2016-02-16 11:46\n"));
//                text.append(PrintUtils.printTwoData("人数：2人", "收银员：张三\n"));
//                text.append("--------------------------------\n");
//
//                text.append(PrintUtils.printThreeData("项目", "数量", "金额\n"));
//                text.append("--------------------------------\n");
//
//                text.append(PrintUtils.printThreeData("面", "1", "0.00\n"));
//                text.append(PrintUtils.printThreeData("米饭", "1", "6.00\n"));
//                text.append(PrintUtils.printThreeData("铁板烧", "1", "26.00\n"));
//                text.append(PrintUtils.printThreeData("一个测试", "1", "226.00\n"));
//                text.append(PrintUtils.printThreeData("牛肉面啊啊", "1", "2226.00\n"));
//                text.append(PrintUtils.printThreeData("牛肉面啊啊啊牛肉面啊啊啊", "888", "98886.00\n"));
//                text.append(PrintUtils.printThreeData("面", "1", "0.00\n"));
//                text.append("--------------------------------\n");
//
//                text.append(PrintUtils.printTwoData("合计", "53.50\n"));
//                text.append(PrintUtils.printTwoData("抹零", "3.50\n"));
//                text.append("--------------------------------\n");
//                text.append(PrintUtils.printTwoData("应收", "50.00\n"));
//                text.append("--------------------------------\n");
//
//                text.append("备注：不要辣、不要香菜");
//                text.append("\n\n\n\n\n");

                imgbp.printText(text.toString());



            }else{//未连接跳转到蓝牙设备列表
                Intent intent = new Intent(mActivity, BluetoothChoiceActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                mActivity.startActivity(intent);

            }


        }

    }

}
